<template>
  <div class="app-container">
    <div v-loading="listLoading" class="control">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="24" :md="14" :lg="12">
          <el-card shadow="hover" class="box-card curr">
            <div v-show="!goods" class="empty">当前暂无拍品开拍</div>
            <template v-if="goods">
              <div class="goods-title">
                <div class="goods-title-left">
                  <div>Lot &nbsp;{{ goods.lot }}</div>
                  <span>{{ goods.name }}</span>
                </div>
                <div class="goods-title-right">
                  <div>起拍价</div>
                  <span>{{ toThousands(goods.start) }}</span>
                </div>
              </div>
              <div class="goods-spec">
                <span v-for="(item, index) in goods.spec" :key="index">{{ item.attr }}: {{ item.val }}</span>
              </div>
              <div class="goods">
                <div class="goods-cover">
                  <img :src="goods&&goods.cover" alt="">
                </div>
                <div class="goods-info">
                  <div class="pre-next">
                    <div v-if="goods" class="price">
                      <div style="text-align:left;font-size:14px;margin-bottom: 5px">{{ goods.state === 2 ? '落槌价' : goods.state === 1 && goods.curr_buyer !== '' ? '当前价' : '起拍价' }}:</div>
                      <small :class="goods.state === 2 && goods.final !== '流拍' ? 'green' : ''">￥</small>
                      <b :class="goods.state === 2 && goods.final !== '流拍' ? 'green' : ''">{{ goods.state === 2 ? toThousands(goods.final) : toThousands(goods.curr) }}</b>
                      <el-tag v-if="goods.curr_buyer !== '' && goods.state > 0 && goods.final !== '流拍'" size="mini" type="info">{{ Number(goods.curr_buyer) === 0 ? '现场' : '网络' }}</el-tag>
                    </div>
                  </div>
                  <div style="font-size: 14px;color: gray">{{ name }}</div>
                </div>
              </div>
            </template>
            <div class="input-box">
              <div class="input-check">
                <el-input v-model.trim="mybid" type="number" :min="0" :disabled="!goods || goods.state !== 1" size="large" placeholder="回车或点击右侧按钮出价" @keyup.enter.native="handleBid(inputBid, 1)">
                  <el-checkbox slot="append" v-model="isSave">保留</el-checkbox>
                </el-input>
                <el-button size="large" :loading="btnLoading" type="primary" :disabled="!goods || goods.state !== 1" @click="handleBid(inputBid, 1)">确认出价</el-button>
              </div>
              <div class="input-btn">
                <el-radio-group v-model="unit" size="large">
                  <el-radio-button :label="10">十</el-radio-button>
                  <el-radio-button :label="100">百</el-radio-button>
                  <el-radio-button :label="1000">千</el-radio-button>
                  <el-radio-button :label="10000">万</el-radio-button>
                  <el-radio-button :label="100000">十万</el-radio-button>
                  <el-radio-button :label="1000000">百万</el-radio-button>
                  <el-radio-button :label="10000000">千万</el-radio-button>
                  <el-radio-button :label="100000000">亿</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </el-card>

          <!-- <div class="broadcast">
            <img src="@/assets/icon-broadcast.png" alt="">
            {{ broadcastMsg }}
          </div> -->
          <el-card shadow="hover" class="box-card bid-area">
            出价:
            <div class="price-box">
              <div class="bid-scroll">
                <div v-for="(item, index) in scrollBids" :key="index" class="bid-scroll-item">
                  <div class="bid-scroll-item-icon" @click="addUnitVal(index)"><i class="el-icon-arrow-up" /></div>
                  <div class="bid-scroll-item-num">{{ item }}</div>
                  <div class="bid-scroll-item-icon" @click="reduceUnitVal(index)"><i class="el-icon-arrow-down" /></div>
                  <div class="bid-scroll-item-unit">{{ scrollBidsUnit[index] }}</div>
                  <div class="bid-scroll-item-clear" @click="clearUnitVal(index)"><i class="el-icon-error" /></div>
                </div>
                <div class="bid-scroll-btn">
                  <el-button size="medium" type="primary" :disabled="!goods || goods.state !== 1" :loading="clickBidLoading" @click="handleBid(clickBid, 3)">出价</el-button>
                </div>
              </div>
            </div>
            <el-divider><i class="el-icon-mouse" /></el-divider>
            <div class="bid-add">
              <el-radio-group v-model="nextbidOp[0]" size="meduim">
                <el-radio :disabled="!goods || goods.state !== 1" :label="1" border>首位</el-radio>
                <el-radio :disabled="!goods || goods.state !== 1" :label="2" border>二位</el-radio>
                <el-radio :disabled="!goods || goods.state !== 1" :label="3" border>三位</el-radio>
              </el-radio-group>
              <el-radio-group v-model="nextbidOp[1]" size="meduim">
                <el-radio :disabled="!goods || goods.state !== 1" :label="1" border>+1</el-radio>
                <el-radio :disabled="!goods || goods.state !== 1" :label="2" border>2, 5, 8</el-radio>
                <el-radio :disabled="!goods || goods.state !== 1" :label="5" border>+5</el-radio>
              </el-radio-group>
              <br>
              <el-button size="medium" type="primary" :loading="nextBtnLoading" :disabled="!goods || goods.state !== 1" @click="handleBid(nextBid, 2)">出价：{{ toThousands(nextBid) }}</el-button>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="0" :sm="0" :md="0" :lg="0">
          <el-card shadow="hover" class="box-card bid-list">
            <div slot="header" class="clearfix bid-th">
              <div>号牌</div><div>出价</div><div>竞拍者</div>
            </div>
            <div id="bidlist" ref="bidlist" class="bid-item-box">
              <div v-for="(item, index) in bids" :key="index" class="bid-item">
                <div>{{ item.num }}</div>
                <div>{{ toThousands(item.bid) }}</div>
                <div>{{ item.buyer_way }}</div>
              </div>
            </div>
          </el-card>
          <el-card shadow="hover" class="box-card">
            <el-table :data="recent" border fit>
              <el-table-column align="center" prop="lot" label="Lot" width="70" />
              <el-table-column align="center" prop="final" label="落槌价">
                <template slot-scope="scope">{{ toThousands(scope.row.final) }}</template>
              </el-table-column>
              <el-table-column align="center" prop="buyer_way" label="竞拍者" width="70" />
              <el-table-column show-overflow-tooltip align="center" prop="buyer_num" label="号牌" />
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getBidcoCurr, postCoBid } from '@/api/ctrl'
import { toThousands } from '@/utils'
export default {
  data () {
    return {
      lotId: '',
      goods: false,
      recent: [],
      listLoading: true,
      bids: [],
      mybid: '',
      nextBtnLoading: false,
      nextbidOp: [1, 1],
      unit: 10000,
      btnLoading: false,
      clickBidLoading: false,
      isSave: false,
      scrollBids: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      scrollBidsUnit: ['十亿', '亿', '千万', '百万', '十万', '万', '千', '百', '十', '个'],
      broadcastMsg: '...'
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ]),
    clickBid () {
      return Number(this.scrollBids.join(''))
    },
    inputBid () {
      if (this.mybid !== '') {
        return this.mybid * this.unit
      } else {
        return ''
      }
    },
    nextBid () {
      if (this.goods && this.goods.state === 1) {
        var curr = Number(this.goods.curr) || 0
        var length = curr.toString().length
        if (this.nextbidOp[1] === 1 || this.nextbidOp[1] === 5) {
          return curr + Math.pow(10, length - this.nextbidOp[0]) * this.nextbidOp[1]
        } else {
          const comp = Number(curr.toString()[this.nextbidOp[0] - 1])
          var od = this.nextbidOp[0]
          if (length < this.nextbidOp[0]) {
            od = length
          }
          var unit = Math.pow(10, (length - od + 1))
          var step = 2
          switch (true) {
            case comp < 2:
              step = 2
              break
            case comp >= 2 && comp < 5:
              step = 5
              break
            case comp >= 5 && comp < 8:
              step = 8
              break
            case comp >= 8:
              step = 10
              break
          }
          return Math.floor(curr / unit) * unit + step * Math.pow(10, length - od)
        }
      } else {
        return ''
      }
    }
  },
  watch: {
    'goods.curr': function () {
      this.setScrollBids(this.goods.curr)
    }
  },
  created () {
    const id = this.$route.params && this.$route.params.id
    this.lotId = id
    this.fetchData()
    this.initWebSocket()
    console.log(this.name)
  },
  mounted () {
    document.addEventListener('visibilitychange', this.handleVisiable)
  },
  destroyed () {
    this.wsSendMsg('leave')
  },
  methods: {
    handleVisiable (e) {
      if (e.target.visibilityState === 'visible') {
        if (!this.global.wsConnected) {
          this.initWebSocket()
        }
      }
    },
    fetchData () {
      this.listLoading = true
      getBidcoCurr(this.lotId).then(res => {
        this.goods = res.data.goods
        this.recent = res.data.recent
        this.bids = res.data.bids.map(el => {
          el.buyer_way = Number(el.num) === 0 ? '现场' : '网络'
          return el
        })
        this.$route.meta.title = `${res.data.name} / 出价面板`
        this.listLoading = false
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    addUnitVal (index) {
      var curr = this.scrollBids[index]
      var val = curr >= 9 ? 0 : curr + 1
      this.scrollBids.splice(index, 1, val)
    },
    reduceUnitVal (index) {
      var curr = this.scrollBids[index]
      var val = curr <= 0 ? 9 : curr - 1
      this.scrollBids.splice(index, 1, val)
    },
    clearUnitVal (index) {
      this.scrollBids.splice(index, 1, 0)
    },
    setScrollBids (val) {
      val = val.toString()
      const str = (Array(10).join(0) + val).slice(-10)
      this.scrollBids = [...`${str}`].map(el => parseInt(el))
    },
    handleBid (bid, from) {
      // 1输入出价 2下口价 3密码锁出价 4强制出价
      if (!bid) {
        this.$message({
          message: '出价不能为空',
          type: 'warning'
        })
        return
      }
      if (from !== 4 && bid <= this.goods.curr) {
        if (this.goods.curr_buyer !== '') {
          this.$message({
            message: '出价不能低于当前价',
            type: 'warning'
          })
          return
        }
        if (this.goods.curr_buyer === '' && bid < this.goods.curr) {
          this.$message({
            message: '出价不能低于起拍价',
            type: 'warning'
          })
          return
        }
      }
      if (from === 1) {
        this.btnLoading = true
      } else {
        this.clickBidLoading = true
      }
      postCoBid({ id: this.goods.id, bid }).then(res => {
        this.btnLoading = false
        this.clickBidLoading = false
        if (!this.isSave) {
          this.mybid = ''
        }
        this.$notify.success({
          message: res.msg
        })
      }).catch(err => {
        console.log(err)
        this.btnLoading = false
        this.clickBidLoading = false
      })
    },
    initWebSocket () {
      const wsData = {
        type: 'join',
        lot_id: this.lotId
      }
      if (this.global.ws) {
        if (this.global.wsConnected) {
          this.global.ws.send(JSON.stringify(wsData))
        }
      } else {
        this.global.ws = new WebSocket(process.env.VUE_APP_WS_HOST)
        this.global.setWs(this.global.ws)
      }
      this.global.ws.onopen = this.wsOnOpen
      this.global.ws.onerror = this.wsOnError
      this.global.ws.onmessage = this.wsOnMessage
      this.global.ws.onclose = this.wsOnClose
    },
    wsOnMessage (e) {
      var data = JSON.parse(e.data)
      // console.log(data)
      const arr = ['willHammer', 'faceLive', 'startAuc', 'cancelAuc', 'dealAuc', 'passAuc', 'reAuc', 'liveBid', 'netBid', 'phoneBid']
      if (Number(data.lot_id) === Number(this.lotId)) {
        switch (true) {
          // 进入、离开专场
          case data.type === 'join' || data.type === 'leave':
            console.log(`${data.uid} ${data.type} 专场 ${this.lotId}`)
            break
          case data.type === 'end':
            console.log(`结束专场 ${this.lotId}`)
            break
          case data.type === 'livePlay':
            console.log(`直播推流：${data.play}`)
            break
          // 更新统计数据
          case data.type === 'count':
            console.log('更新控制台实时统计数据！')
            break
          // 拍品操作客户端广播
          case arr.indexOf(data.type) > -1:
            console.log('客户端广播: ' + data.msg)
            // this.broadcastMsg = data.msg
            if (data.goods || data.goods === false) {
              this.goods = data.goods
              if (data.type === 'dealAuc' && data.goods.curr_buyer === this.name) {
                this.$message({
                  message: '恭喜您成交！',
                  type: 'success'
                })
              }
            }
            if (data.recent) {
              if (this.recent.length >= 3) {
                this.recent.shift()
              }
              this.recent.push(data.recent)
            }
            if (data.type === 'reAuc' || data.type === 'startAuc') {
              this.bids = []
            }
            break
          // 出价更新出价列表 撤销出价
          case data.type === 'bid' || data.type === 'revoke':
            var { num, bid } = data
            var way = Number(num) === 0 ? '现场' : '网络'
            this.goods.curr = bid
            this.goods.curr_buyer = num
            if (data.type === 'bid') {
              this.bids.unshift({ num, bid, buyer_way: way })
              this.disRevokeBtn = false
            } else {
              this.bids.shift()
            }
            // this.scrollBidList()
            console.log(`${way}出价：${this.toThousands(bid)}`)
            break
        }
      }
    },
    wsOnOpen () {
      console.log('组件内WebSocket连接成功!')
      this.global.wsConnected = true
      this.wsSendMsg('join')
    },
    wsOnError (e) {
      console.log('组件内WebSocket连接发生错误!')
      this.global.wsConnected = false
    },
    wsOnClose () {
      console.log('组件内WebSocket连接关闭!')
      this.global.wsConnected = false
      this.global.ws = new WebSocket(process.env.VUE_APP_WS_HOST)
      this.global.setWs(this.ws)
    },
    wsSendMsg (type) {
      if (this.global.ws && this.global.wsConnected) {
        var msg = {
          type,
          lot_id: this.lotId
        }
        this.global.ws.send(JSON.stringify(msg))
      }
    },
    toThousands,
    scrollBidList () {
      setTimeout(() => {
        this.$refs.bidlist.scrollTop = this.bids.length * 40 - 30
      }, 0)
    }
  }
}
</script>

<style lang="scss" scoped>
.control {
  width: 100%;
  max-width: 1250px;
  .green {
    color: green !important;
  }
  .box-card {
    margin-bottom: 15px;
    .empty {
      color: #666;
      text-align: center;
      font-size: 14px;
    }
  }
  .curr {
    .goods-title {
      display: flex;
      font-weight: 600;
      justify-content: space-between;
      span {
        line-height: 1.5;
      }
      &-left {
        font-size: 18px;
      }
      &-right {
        font-size: 16px;
        text-align: center;
        span {
          font-size: 18px;
          color: #ca2828;
        }
      }
    }
    .goods-spec {
      font-size: 14px;
      color: #555;
      margin: 10px 0;
      span {
        margin-right: 10px;
      }
    }
    .goods {
      display: flex;
      margin-bottom: 15px;
      &-cover {
        width: 220px;
        max-height: 230px;
        display: flex;
        align-items: center;
        overflow: hidden;
        margin-right: 25px;
        padding: 5px;
        border: 2px solid #333;
        border-radius: 3px;
        img {
          width: 100%;
          height: auto;
        }
      }
      &-info {
        max-height: 300px;
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        p {
          line-height: 1.3;
        }
        .pre-next {
          display: flex;
          margin-bottom: 10px;
          justify-content: space-between;
          align-items: center;
        }
        .btns {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;
          // justify-content: flex-start;
          .el-button {
            margin-bottom: 10px;
          }
          .el-button+.el-button {
            margin-left: 0;
          }
        }
      }
    }
    .input-box {
      // width: fit-content;
      margin: 0 auto 20px;
      .input-check {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .el-input {
        margin-right: 14px;
      }
      .el-radio-group {
        width: 100%;
        margin: 10px 10px 0 0px;
        .el-radio-button {
          width: 12.5%;
        }
      }
      .input-btn {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
    }

    .price {
      text-align: center;
      padding: 5px 0 10px;
      small {
        color: firebrick;
        font-size: 14px;
      }
      b {
        font-size: 30px;
        color: rgb(202, 40, 40);
        margin: 0 5px 0 0;
        vertical-align: -3px;
      }
    }

    // .btns {
    //   display: flex;
    //   flex-wrap: wrap;
    //   justify-content: space-around;
    //   .el-button {
    //     margin-bottom: 10px;
    //   }
    // }
  }
  .broadcast {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    img {
      width: 24px;
      margin-right: 5px;
    }
  }
  .price-box {
    display: flex;
    justify-content: space-between;
    align-items:center;
    margin-top: 20px;
  }
  .bid-scroll {
    width: 100%;
    max-width: 560px;
    margin: auto;
    display: flex;
    align-items: center;
    &-item {
      width: 42px;
      text-align: center;
      border: 1px solid #ccc;
      border-right: none;
      &:nth-last-of-type(2) {
        margin-right: 15px;
        border-right: 1px solid #ccc;
      }
      &-num {
        font-size: 20px;
        color: green;
        font-weight: bold;
        line-height: 1.4;
        border-top: 1px solid #dcdfe6;
        border-bottom: 1px solid #dcdfe6;
      }
      &-icon {
        padding: 4px 0;
        font-weight: 600;
        font-size: 12px;
        background: #f5f7fa;
        &:hover {
          cursor: pointer;
          color: #009788;
        }
      }
      &-unit {
        font-size: 12px;
        line-height: 2;
        border-top: 1px solid #dcdfe6;
      }
      &-clear {
        color: gray;
        padding-bottom: 2px;
        &:hover {
          cursor: pointer;
          color: #009788;
        }
      }
    }
    &-btn {
      display: flex;
      flex-direction: column;
      .el-button {
        margin-left: 15px;
        margin-bottom: 10px;
      }
    }
  }
  .bid-list {
    .bid-item-box {
      height: 160px;
      overflow-y: scroll;
    }
    .bid-th, .bid-item{
      background: #b8bcc4;
      display: flex;
      text-align: center;
      div {
        padding: 12px 0;
        border-right: 1px solid #eee;
        &:first-of-type {
          width: 30%;
        }
        &:last-of-type {
          width: 30%;
          border-right: none;
        }
        &:nth-of-type(2) {
          flex: 1;
        }
      }
    }
    .bid-item {
      color: #606266;
      font-size: 14px;
      background: #fff;
      border-bottom: 1px solid #eee;
      &:last-of-type {
        border: none;
      }
      div {
        padding: 12px 0;
        border-right: none;
      }
    }
  }
  .bid-area {
    .bid-add {
      text-align: center;
      .el-radio {
        width: 100px;
        margin-bottom: 15px;
      }
    }
  }
  .lot-info {
    .lot-name {
      margin-bottom: 10px;
      span {
        margin-right: 10px;
      }
    }
    .lot-live {
      display: flex;
      margin: 15px 0 0;
      width: 470px;
      align-items: center;
      .el-button {
        width: 60px;
        margin: 0 10px;
        display: block;
      }
      img {
        width: 24px;
        height: 100%;
        border-radius: 10%;
        display: block;
      }
    }
    .lot-num {
      font-size: 14px;
      line-height: 1.5;
      &:nth-of-type(3) {
        margin-top: 15px;
      }
      span {
        margin-right: 20px;
      }
    }
  }
}
</style>
<style lang="scss">
.control {
  .el-card__header {
    padding: 15px;
    font-weight: bold;
  }
  .el-card__body {
    padding: 15px;
  }

  .bid-list {
    .el-card__header {
      padding: 0;
    }
    .el-card__body {
      padding: 0;
    }
  }
  .goods-list {
    .el-table--medium td, .el-table--medium th {
      padding: 6px 0;
      cursor: pointer;
    }
    td.goods-name-td .cell {
      color: rgb(81, 81, 206);
      text-decoration: underline;
    }
    .el-table .dis-row {
      background: #f0f9eb;
    }
  }
  .el-input.is-disabled .el-input__inner {
    background: #fff;
    color: #606266;
  }
  .el-radio-button__inner {
    width: 100%;
    padding: 10px 0;
    text-align: center;
  }
}
</style>
